package server

import (
	"chitchat_http/model"
	"chitchat_http/util"
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"github.com/doujunyu/gogo/utility"
	"os"
	"strings"
)

// MusicByList 音乐列表
func MusicByList(page string, limit string, title string) []map[string]interface{} {
	musicSql, args := sql_aid.PgTable(model.TableByMusic).WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		if i[0].(string) != ""{
			query.Where("title like ?", i[0].(string)+"%")
		}
	},title).OrderBy("id desc").PageSize(page, limit).ToSql()
	musicData, err := sql_aid.DataToMap(model.PgSql.Query(musicSql, args...))
	if err != nil {
		gogo_log.Error("server_MusicByList", "查询数据失败", err.Error())
		return []map[string]interface{}{}
	}
	http := os.Getenv("SERVER_HTTP")
	for _, datum := range musicData {
		datum["file_url"] = util.IsPicturePath(datum["file_url"].(string),http)
	}

	return musicData
}

func MusicByAdd(title string, authorId int64, teamId int64 ,fileUrl string)error {
	//查找作家名字
	authorSql, args := sql_aid.PgTable(model.TableByMusicAuthor).Where("id = ?",authorId).ToSql()
	authorData, err := sql_aid.DataToMap(model.PgSql.Query(authorSql, args...))
	if err != nil || len(authorData) == 0 {
		return errors.New("作者不存在")
	}
	//音乐文件更改起名，把带有空格的转译
	fileTitle := strings.Replace(title, " ", "·", -1)
	fileAuthor := strings.Replace(authorData[0]["name"].(string), " ", "·", -1)
	//数据库数据
	data := make(map[string]interface{})
	data["title"] = title
	data["author"] = authorData[0]["name"].(string)
	//查找乐队名字
	if teamId != 0{
		teamSql, args := sql_aid.PgTable(model.TableByMusicTeam).Where("id = ?",teamId).ToSql()
		teamData, err := sql_aid.DataToMap(model.PgSql.Query(teamSql, args...))
		if err != nil || len(teamData) == 0 {
			return errors.New("乐队不存在")
		}
		//重置文件名
		fileTeam := strings.Replace(teamData[0]["name"].(string), " ", "·", -1)
		data["file_url"] = fmt.Sprintf("%s/%s/%s-%s.mp3",os.Getenv("FILE_PATH"),model.MusicFile,fileTeam,fileTitle)
		//重置作者名为乐队名
		data["author"] = teamData[0]["name"]
		//设置所属人员
		teamAuthorSql, args := sql_aid.PgTable(model.TableByMusicTeamAuthor).Where("team_id = ?",teamId).ToSql()
		teamAuthorData, err := sql_aid.DataToMap(model.PgSql.Query(teamAuthorSql, args...))
		if err != nil || len(teamAuthorData) == 0 {
			return errors.New("乐队中没有成员")
		}
		music_team_ids := util.ArrayField(&teamAuthorData,"author_id")
		data["music_author_id"] = model.MusicByMusicAuthorIdToJson(music_team_ids...)
		data["music_team_id"] = teamId
	}else{
		data["file_url"] = fmt.Sprintf("%s/%s/%s-%s.mp3",os.Getenv("FILE_PATH"),model.MusicFile,fileAuthor,fileTitle)
		data["music_author_id"] = model.MusicByMusicAuthorIdToJson(authorId)
		data["music_team_id"] = 0
	}
	//fmt.Println(fileUrl,pictureNewPath)

	//写入数据库中
	tx, err := model.PgSql.Begin()
	defer tx.Rollback()

	dataSql,args := sql_aid.PgTable(model.TableByMusic).InsertByMap(data)
	_,err = tx.Exec(dataSql,args...)
	if err != nil {
		gogo_log.Error("server_MusicByAdd", "歌曲添加错误", err.Error())
		return errors.New("添加错误")
	}
	_,err = utility.CopyFile("."+data["file_url"].(string),"."+fileUrl)
	if err != nil{
		return err
	}
	tx.Commit()
	return nil
}


// MusicByIds 音乐ID找数据
func MusicByIds(musicIds string) []map[string]interface{} {
	if musicIds == ""{
		return []map[string]interface{}{}
	}
	split := strings.Split(musicIds, ",")
	splitByInterface := make([]interface{},0)
	for _, s := range split {
		splitByInterface = append(splitByInterface,s)
	}
	musicSql, args := sql_aid.PgTable(model.TableByMusic).WhereIn("id",splitByInterface...).ToSql()
	musicData, err := sql_aid.DataToMap(model.PgSql.Query(musicSql, args...))
	if err != nil {
		gogo_log.Error("server_MusicByList", "查询数据失败", err.Error())
		return []map[string]interface{}{}
	}
	musicDataByKey := util.ArrayColumnByInt64(&musicData,"id")
	http := os.Getenv("SERVER_HTTP")
	data := make([]map[string]interface{},0)
	for _, datum := range split {
		key := util.StringToInt64(datum)
		musicDataByKey[key]["file_url"] = util.IsPicturePath(musicDataByKey[key]["file_url"].(string),http)
		data = append(data,musicDataByKey[key])
	}
	return musicData
}

// MusicBySearchTitle 音乐搜索
func MusicBySearchTitle(title string) []map[string]interface{} {
	musicSql, args := sql_aid.PgTable(model.TableByMusic).Where("title like ?", title+"%").ToSql()
	musicData, err := sql_aid.DataToMap(model.PgSql.Query(musicSql, args...))
	if err != nil {
		gogo_log.Error("server_MusicByList", "查询数据失败", err.Error())
		return []map[string]interface{}{}
	}
	http := os.Getenv("SERVER_HTTP")
	for _, datum := range musicData {
		datum["file_url"] = util.IsPicturePath(datum["file_url"].(string),http)
	}
	return musicData
}

// MusicLikeByList 我的喜欢
func MusicLikeByList(userId int64) []map[string]interface{} {
	data,err  := model.MusicLikeByList(userId)
	if err != nil {
		gogo_log.Error("server_MusicLikeByJoin", "查询数据失败", err.Error())
		return []map[string]interface{}{}
	}
	return data
}

// MusicLikeByJoin 标记喜欢
func MusicLikeByJoin(userId int64, musicId int64) error {
	err := model.MusicLikeByJoin(userId, musicId)
	if err != nil {
		gogo_log.Error("server_MusicLikeByJoin", "查询数据失败", err.Error())
		return errors.New("执行失败")
	}
	return nil
}

// MusicLikeByExit 取消喜欢
func MusicLikeByExit(userId int64, musicLikeId int64) error {
	err := model.MusicLikeByExit(userId, musicLikeId)
	if err != nil {
		gogo_log.Error("server_MusicLikeByJoin", "查询数据失败", err.Error())
		return errors.New("执行失败")
	}
	return nil
}
